import type { Ref } from 'vue'
import { downloadFile, saveFileToDevice, getSaveFileInfoOnTheDevice, removeSaveFileOnTheDevice } from '@/utils'
import { updatePathLocalData } from '@/utils/storage/local-data'
const wgt = 'https://nfile.webnotepad.net/uploads/20231208/fb098d573a1f87a942e5475074faa120.wgt'
const apk = 'https://nfile.webnotepad.net/uploads/20231208/ae118fc1ee663ac63eccbffe37445311.apk'

/* 假定字符串的每节数都在5位以下 */
function toNum(a: string) {
  var a = a.toString()
  var c = a.split('.')
  var num_place = ['', '0', '00', '000', '0000'],
    r = num_place.reverse()
  for (var i = 0; i < c.length; i++) {
    var len = c[i].length
    c[i] = r[len] + c[i]
  }
  var res = c.join('')
  return res
}

/* 根据版本号返回是否需要更新 */
function isNeedUpdate(oldVersion: string, newVersion: string) {
  const versionOriginal = toNum(oldVersion),
    versionNow = toNum(newVersion)
  return versionNow > versionOriginal
}

// 检查是否需要更新
export const checkNeedUpdate = (dialog: any) => {
  // #ifdef APP-PLUS
  const apiData = {
    maskCloseAble: false,
    extraData: {
      forceUpdate: false,
      content:
        '1. 开放一键采集功能开放一键采集功开放一键采集功开放一键采集功\n2. 修复部分车辆生成海报错误问题\n3. 替换扫码组件\n4. 部分样式调整\n1. 开放一键采集功能\n2. 修复部分车辆生成海报错误问题\n3. 替换扫码组件\n4. 部分样式调整',
      fileUrl: apk,
      type: 1,
      version: '1.0.1'
    }
  }
  plus.runtime.getProperty(plus.runtime.appid!, function (inf) {
    const version = inf.version!
    if (isNeedUpdate(version, apiData.extraData.version)) {
      // 需要进行更新
      dialog.show(apiData)
    } else if (updatePathLocalData.get() && updatePathLocalData.get().version === version) {
      // 不需要更新时如果有旧的资源包则进行删除
      updatePathLocalData.clear()
      removeSaveFileOnTheDevice(updatePathLocalData.get().filePath)
      console.log('删除资源包')
    }
  })
  // #endif
}

// 前往AppStore市场
export const toAppStore = () => {
  plus.runtime.launchApplication(
    {
      action: `itms-apps://itunes.apple.com/cn/app/id1528287388?mt=8`
    },
    function (e) {
      console.log('Open system default browser failed: ' + e.message)
    }
  )
}

// 检查资源是否已经存在
export const checkIsDownLoad = (version: string): Promise<string> => {
  return new Promise(async (resolve, reject) => {
    if (updatePathLocalData.get() && updatePathLocalData.get().version === version) {
      const res = await getSaveFileInfoOnTheDevice(updatePathLocalData.get().filePath)
      if (res) {
        resolve(updatePathLocalData.get().filePath)
        return false
      } else {
        reject()
        updatePathLocalData.clear()
      }
    } else {
      reject()
      updatePathLocalData.clear()
    }
  })
}

// 下载更新包
export const downLoadApkFile = (
  fileUrl: string,
  version: string,
  fileTotalSize: Ref<string>,
  curFileSize: Ref<string>,
  updateProgress: Ref<number>
): Promise<string> => {
  return new Promise((resolve, reject) => {
    downloadFile(fileUrl, (downloadTask: UniApp.DownloadTask) => {
      downloadTask.onProgressUpdate(res => {
        fileTotalSize.value = sizeComputed(res.totalBytesExpectedToWrite)
        curFileSize.value = sizeComputed(res.totalBytesWritten)
        updateProgress.value = res.progress
      })
    })
      .then(async res => {
        resolve(res)
        // 下载完成将临时文件保存到本地，下次直接进行安装不用进行下载
        const filePath = await saveFileToDevice(res)
        updatePathLocalData.set({
          version: version,
          filePath
        })
      })
      .catch(err => {
        reject(err)
      })
  })
}

const sizeComputed = (size: number) => {
  const v = Math.ceil(size / 1024)
  if (v >= 1000) {
    return (v / 1000).toFixed(2) + 'M'
  } else {
    return v + 'kb'
  }
}

export const install = (fileType: 'apk' | 'wgt'): Promise<void> => {
  // #ifdef APP-PLUS
  return new Promise((resolve, reject) => {
    const filePath = updatePathLocalData.get().filePath
    plus.runtime.install(
      filePath,
      { force: true },
      () => {
        resolve()
        if (fileType === 'wgt') {
          plus.runtime.restart()
        }
      },
      () => {
        updatePathLocalData.clear()
        removeSaveFileOnTheDevice(filePath)
        reject()
      }
    )
  })
  // #endif
}
